import { loginApi, logoutApi } from "@/api/auth";
import { getUserInfoApi } from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";

import { LoginData } from "@/api/auth/types";
import { UserInfo } from "@/api/user/types";
import { loginApiPr } from "@/api/porray/api";
import { userTestData } from "@/store/modules/allRoutesData";

//  想要Pinia使用必须先引入 defineStore
export const useUserStore = defineStore("user", () => {
  /*
   *pinia: state
   * */
  const user: UserInfo = {
    roles: [],
    perms: [],
  };

  /*
   * pinia :action
   * */
  /**
   * 登录请求封装函数
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then((response) => {
          const { tokenType, accessToken } = response.data;
          localStorage.setItem("testtoken", tokenType + " " + accessToken); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          localStorage.setItem("token", tokenType + " " + accessToken); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * porray 登录请求封装函数
   *
   * @returns
   */
  function loginPr() {
    return new Promise<void>((resolve, reject) => {
      loginApiPr("admin@1809", "password")
        .then((response) => {
          console.log("|--登录返回", response);
          localStorage.setItem("token", response.data.response.token); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          localStorage.setItem("testtoken", response.data.response.token); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          localStorage.setItem("expiresin", response.data.response.expires_in); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          resolve(response);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合),动态改成静态
  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      Object.assign(user, { ...userTestData });
      resolve({});
    });
  }

  // user logout
  function logout() {
    return new Promise<void>((resolve, reject) => {
      localStorage.setItem("testtoken", "");
      localStorage.setItem("token", "");
      location.reload(); // 清空路由
      resolve();
    });
  }

  // remove token
  function resetToken() {
    console.log("resetToken");
    return new Promise<void>((resolve) => {
      localStorage.setItem("testtoken", "");
      localStorage.setItem("token", "");
      resetRouter();
      resolve();
    });
  }

  return {
    // state
    user,

    // action
    login,
    getUserInfo,
    logout,
    resetToken,

    //   porray
    loginPr,
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
